#!/usr/bin/env node

/**
 * 数据库连接测试脚本
 * 测试MariaDB连接和基本查询功能
 */

const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 读取配置文件
const configPath = path.join(__dirname, '../config.json');
let config;

try {
    const configData = fs.readFileSync(configPath, 'utf8');
    config = JSON.parse(configData);
} catch (error) {
    console.error('❌ 无法读取配置文件:', error.message);
    process.exit(1);
}

// 获取当前数据库配置
const currentDbTag = config['current-db'];
const dbConfig = config['database-set'].find(db => db.database_tag === currentDbTag);

if (!dbConfig) {
    console.error(`❌ 找不到数据库配置: ${currentDbTag}`);
    process.exit(1);
}

console.log(`🔗 连接到数据库: ${dbConfig.database_tag} (${dbConfig.database})`);

async function testDatabaseConnection() {
    let connection;
    
    try {
        // 创建数据库连接
        connection = await mysql.createConnection({
            host: dbConfig.host,
            port: parseInt(dbConfig.port),
            user: dbConfig.user,
            password: dbConfig.password,
            database: dbConfig.database,
            charset: dbConfig.charset,
            timezone: dbConfig.timezone
        });

        console.log('✅ 数据库连接成功!');

        // 测试基本查询
        console.log('\n📊 数据库统计信息:');
        
        // 查询表数量
        const [tables] = await connection.execute('SHOW TABLES');
        console.log(`📋 表总数: ${tables.length}`);
        
        // 查询用户数量
        const [users] = await connection.execute('SELECT COUNT(*) as count FROM users');
        console.log(`👥 用户数量: ${users[0].count}`);
        
        // 查询商机数量
        const [opportunities] = await connection.execute('SELECT COUNT(*) as count FROM opportunities');
        console.log(`💼 商机数量: ${opportunities[0].count}`);
        
        // 查询风险数量
        const [risks] = await connection.execute('SELECT COUNT(*) as count FROM risks');
        console.log(`⚠️  风险数量: ${risks[0].count}`);
        
        // 查询商机状态分布
        const [statusDist] = await connection.execute(`
            SELECT status, COUNT(*) as count 
            FROM opportunities 
            GROUP BY status 
            ORDER BY count DESC
        `);
        
        console.log('\n📈 商机状态分布:');
        statusDist.forEach(item => {
            console.log(`   ${item.status}: ${item.count}`);
        });
        
        // 查询高价值商机
        const [highValue] = await connection.execute(`
            SELECT customer_name, opportunity_name, value, status 
            FROM opportunities 
            WHERE value > 2000000 
            ORDER BY value DESC
        `);
        
        console.log('\n💰 高价值商机 (>200万):');
        highValue.forEach(opp => {
            console.log(`   ${opp.customer_name} - ${opp.opportunity_name}: ¥${opp.value.toLocaleString()} [${opp.status}]`);
        });
        
        console.log('\n✅ 数据库测试完成!');
        
    } catch (error) {
        console.error('❌ 数据库操作失败:', error.message);
        process.exit(1);
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 执行测试
testDatabaseConnection();
